﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using ThousandFunClient.model;
using ThousandFunClient.Util;
using System.Collections;
using System.IO.Ports;
using System.Timers;
using log4net;
using System.Globalization;

namespace ThousandFunClient
{
    public partial class Fm_ToolsNet : Form
    {
        public Fm_ToolsNet()
        {
            InitializeComponent();
        }

        private IPEndPoint ServerInfo;
        private Socket ClientSocket;
        //信息接收缓存
        private Byte[] MsgBuffer;


        private ToolsNetResponse toolsNetResponse08;

        IPEndPoint ServerInfoData;
        
        private string dataPortNum;

        private Socket ClientSocketData;

        //信息接收缓存
        private Byte[] MsgBufferData;

        private static string watchpath = System.Configuration.ConfigurationSettings.AppSettings["toolsnetwatchpath"];

        private static string nowchangepathfile = "";
        private static string nowchangefile = "";
        //纪录的run文件
        private static string recordrunfile = watchpath + "\\" + System.Configuration.ConfigurationSettings.AppSettings["recordrunfile"];
        private static string recordrunfilerow = System.Configuration.ConfigurationSettings.AppSettings["recordrunfilerow"];
        //今天的理论应该run的文件
        private static string nowdatefile = DateUtil.GetInstance().CurrentTime.ToString("d") + "_SG1.csv";

        System.Timers.Timer timer_keepalive; //= new System.Timers.Timer()

        private static bool connectToolsnet = false;

        CsvStreamReader csvStreamReader;

        private void CmdEnter_Click(object sender, EventArgs e)
        {
            //定义一个IPV4，TCP模式的Socket
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            MsgBuffer = new Byte[65535];
            
            //允许子线程刷新数据
            CheckForIllegalCrossThreadCalls = false;

            ServerInfo = new IPEndPoint(IPAddress.Parse(ConfigUtil.GetToolsNetIP()), 6575);

            uint IOC_IN = 0x80000000;
            uint IOC_VENDOR = 0x18000000;
            uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
            byte[] outValue = BitConverter.GetBytes(0);

            try
            {
                ClientSocket.Connect(ServerInfo);
                ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);

            }
            catch (Exception ex)
            {
                Constants.syslogger.Error("连接服务器失败，请确认配置和服务器是否正常工作！", ex);
                MessageBox.Show("连接服务器失败，请确认配置和服务器是否正常工作！");
            }
        }

        private void ReceiveCallBack(IAsyncResult AR)
        {
            string retseqstr;
            //信息发送存储
            Byte[] MsgSend;
            ToolsNetResponse toolsNetResponse;
            try
            {
                //结束挂起的异步读取，返回接收到的字节数。 AR，它存储此异步操作的状态信息以及所有用户定义数据
                int REnd = ClientSocket.EndReceive(AR);
                byte[] brec = new byte[REnd];
                for (int i = 0; i < REnd; i++)
                {
                    brec[i] = MsgBuffer[i];
                }
                lock (this.RecieveMsg)
                {
                    Constants.syslogger.Error("receive");
                    Constants.syslogger.Error(brec);
                    retseqstr = System.Text.Encoding.ASCII.GetString(brec);
                    toolsNetResponse = new ToolsNetResponse(retseqstr);
                    Constants.syslogger.Error(retseqstr);
                    this.RecieveMsg.AppendText(Encoding.Unicode.GetString(MsgBuffer, 0, REnd));

                }
                if (toolsNetResponse.ResultCMD.Equals("12"))
                {
                    string seqnum = ToolsNetUtil.makelenstr(ToolsNetUtil.make05str(toolsNetResponse.Identifier12));//+ make07str(retseqstr.Substring(6, 5))

                    byte[] array = new byte[seqnum.Length];   //定义一组数组array
                    MsgSend = System.Text.Encoding.ASCII.GetBytes(seqnum); //string转换的字母
                    string seqnum07 = ToolsNetUtil.makelenstr(ToolsNetUtil.make07str(toolsNetResponse.Identifier12));
                    byte[] MsgSend07 = System.Text.Encoding.ASCII.GetBytes(seqnum07);

                    ClientSocket.Send(MsgSend);
                    ClientSocket.Send(MsgSend07);
                    ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
                }
                if (toolsNetResponse.ResultCMD.Equals("08"))
                {
                    toolsNetResponse08 = toolsNetResponse;
                    this.CmdSend_Click(null, null);
                }

            }
            catch (Exception ex)
            {
                Constants.syslogger.Error(ex);
                MessageBox.Show("已经与服务器断开连接！");
                this.Close();
            }

        }

        private void CmdSend_Click(object sender, EventArgs e)
        {
            //定义一个IPV4，TCP模式的Socket
            ClientSocketData = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            MsgBufferData = new Byte[65535];

            //允许子线程刷新数据
            CheckForIllegalCrossThreadCalls = false;

            ServerInfoData = new IPEndPoint(IPAddress.Parse(ConfigUtil.GetToolsNetIP()), Int32.Parse(toolsNetResponse08.TnPortNumber08));

            uint IOC_IN = 0x80000000;
            uint IOC_VENDOR = 0x18000000;
            uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
            byte[] outValue = BitConverter.GetBytes(0);

            try
            {
                ClientSocketData.Connect(ServerInfoData);

                string seqnum01 = ToolsNetUtil.makelenstr(ToolsNetUtil.make01str(toolsNetResponse08));
                byte[] MsgSend01 = System.Text.Encoding.ASCII.GetBytes(seqnum01);

                string seqnum02 = ToolsNetUtil.makelenstr(ToolsNetUtil.make02str(toolsNetResponse08));
                byte[] MsgSend02 = System.Text.Encoding.ASCII.GetBytes(seqnum02);

                //string[] ccc = " , ,5,7,0,1,9,0,0,0,1, , , ,3, , , ,1, , , , ,1,0,.,4,0,.,2,0,.,2,0,A,r,e,a, ,3,2, , , , , , , , , , , , , , , , , , , , ".Split(',');

                //byte[] gesend01 = new byte[ccc.Length];

                //for (int i = 0; i < ccc.Length; i++)
                //{
                //    gesend01[i] = System.Text.Encoding.ASCII.GetBytes(ccc[i])[0];
                //}

                //string[] fbc = " ,2,4,9,0,2,9,0,0,0,2, , , ,3, , , ,1, , , ,2, , , , ,1,0,.,4,0,.,2,0,.,1,0,T,a,k,t, ,1,1,2, , , , , , , , , , , , , , , , , , , , ,3, , , ,1,B,r,a,k,e, ,l,e,f,t, , , , , , , , , , , , , , , , , , ,1, , , ,1,L,e,f,t, ,s,i,d,e, , , , , , , , , , , , , , , , , , , ,2,B,r,a,k,e, ,r,i,g,h,t, , , , , , , , , , , , , , , , , ,1, , , ,1,R,i,g,h,t, ,s,i,d,e, , , , , , , , , , , , , , , , , , ,3,S,t,e,e,r,i,n,g, ,w,h,e,e,l, , , , , , , , , , , , , , ,1, , , ,2,C,e,n,t,r,a,l, ,b,o,l,t, , , , , , , , , , , , , ".Split(',');

                //byte[] gesend02 = new byte[fbc.Length];

                //for (int i = 0; i < fbc.Length; i++)
                //{
                //    gesend02[i] = System.Text.Encoding.ASCII.GetBytes(fbc[i])[0];
                //}

                ClientSocketData.Send(MsgSend01);
                ClientSocketData.Send(MsgSend02);

                //ClientSocketData.Send(gesend01);
                //ClientSocketData.Send(gesend02);

                ClientSocketData.BeginReceive(MsgBufferData, 0, MsgBufferData.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBackData), null);


            }
            catch (Exception ex)
            {
                Constants.syslogger.Error("连接服务器失败，请确认配置和服务器是否正常工作！", ex);
                MessageBox.Show("连接服务器失败，请确认配置和服务器是否正常工作！");
            }
        }

        private void CmdExit_Click(object sender, EventArgs e)
        {
            byte[] outValue;
            
           string xx = " ,  , 5, 7, 0, 1, 9, 0, 0, 0, 1,  ,  ,  , 3,  ,  ,  , 1,  ,  ,  ,  , 1, 0, ., 4, 0, ., 2, 0, ., 2, 0, A, r, e, a,  , 3, 2,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ";

           string[] xxc = "0,0,0,7,1,2,0,0,1,1,0".Split(',');

           outValue = new byte[xxc.Length];

           for (int i = 0; i < xxc.Length;i++ )
           {
               outValue[i] = System.Text.Encoding.ASCII.GetBytes(xxc[i])[0];
           }


           string[] ccc = " , ,5,7,0,1,9,0,0,0,1, , , ,3, , , ,1, , , , ,1,0,.,4,0,.,2,0,.,2,0,A,r,e,a, ,3,2, , , , , , , , , , , , , , , , , , , , ".Split(',');

           byte[] gesend01 = new byte[ccc.Length];

           for (int i = 0; i < ccc.Length; i++)
           {
               gesend01[i] = System.Text.Encoding.ASCII.GetBytes(ccc[i])[0];
           }

           string[] fbc = " ,2,4,9,0,2,9,0,0,0,2, , , ,3, , , ,1, , , ,2, , , , ,1,0,.,4,0,.,2,0,.,1,0,T,a,k,t, ,1,1,2, , , , , , , , , , , , , , , , , , , , ,3, , , ,1,B,r,a,k,e, ,l,e,f,t, , , , , , , , , , , , , , , , , , ,1, , , ,1,L,e,f,t, ,s,i,d,e, , , , , , , , , , , , , , , , , , , ,2,B,r,a,k,e, ,r,i,g,h,t, , , , , , , , , , , , , , , , , ,1, , , ,1,R,i,g,h,t, ,s,i,d,e, , , , , , , , , , , , , , , , , , ,3,S,t,e,e,r,i,n,g, ,w,h,e,e,l, , , , , , , , , , , , , , ,1, , , ,2,C,e,n,t,r,a,l, ,b,o,l,t, , , , , , , , , , , , , ".Split(',');

           byte[] gesend02 = new byte[fbc.Length];

           for (int i = 0; i < fbc.Length; i++)
           {
               gesend02[i] = System.Text.Encoding.ASCII.GetBytes(fbc[i])[0];
           }

           string seqnum01 = ToolsNetUtil.makelenstr(ToolsNetUtil.make01str(toolsNetResponse08));
            byte[] MsgSend01 = System.Text.Encoding.ASCII.GetBytes(seqnum01);

            string seqnum02 = ToolsNetUtil.makelenstr(ToolsNetUtil.make02str(toolsNetResponse08)); ;
            byte[] MsgSend02 = System.Text.Encoding.ASCII.GetBytes(seqnum02);

            //ClientSocketData.Send(MsgSend01);
            //ClientSocketData.Send(MsgSend02);


            ClientSocketData.Send(gesend01);
            ClientSocketData.Send(gesend02);
        }



        private void ReceiveCallBackData(IAsyncResult AR)
        {
            string retseqstr;
            //信息发送存储
            //Byte[] MsgSend;
            ToolsNetResponse toolsNetResponse;
            try
            {
                //结束挂起的异步读取，返回接收到的字节数。 AR，它存储此异步操作的状态信息以及所有用户定义数据
                int REnd = ClientSocketData.EndReceive(AR);
                byte[] brec = new byte[REnd];
                for (int i = 0; i < REnd; i++)
                {
                    brec[i] = MsgBufferData[i];
                }
                lock (this.RecieveMsg)
                {
                    Constants.syslogger.Error("receive");
                    Constants.syslogger.Error(brec);
                    retseqstr = System.Text.Encoding.ASCII.GetString(brec);
                    toolsNetResponse = new ToolsNetResponse(retseqstr);
                    Constants.syslogger.Error(retseqstr);
                    this.RecieveMsg.AppendText(Encoding.Unicode.GetString(MsgBuffer, 0, REnd));

                }
                if (toolsNetResponse.ResultCMD.Equals("05"))
                {
                    if (toolsNetResponse.Identifier05.Equals("60000"))
                    {
                        Constants.syslogger.Error("keepalive");
                    }


                    //string seqnum06 = ToolsNetUtil.makelenstr(ToolsNetUtil.make06str());
                    //byte[] MsgSend06 = System.Text.Encoding.ASCII.GetBytes(seqnum06);
                    //ClientSocketData.Send(MsgSend06);

                    //ClientSocketData.BeginReceive(MsgBufferData, 0, MsgBufferData.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBackData), null);

                }

            }
            catch (Exception ex)
            {
                Constants.syslogger.Error(ex);
                MessageBox.Show("已经与服务器断开连接！");
                this.Close();
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            CsvStreamReader csvStreamReader = new CsvStreamReader("C:\\20130303\\CSV\\2013-02-28_SG1.csv");
            int i = csvStreamReader.ColCount;
            int ig = csvStreamReader.RowCount;
        }

        private void Fm_ToolsNet_Load(object sender, EventArgs e)
        {
            // Create a new FileSystemWatcher and set its properties.
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = watchpath;
            /* Watch for changes in LastAccess and LastWrite times, and 
               the renaming of files or directories. */
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
               | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            // Only watch text files.
            watcher.Filter = "*.csv";

            // Add event handlers.
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            //watcher.Deleted += new FileSystemEventHandler(OnChanged);
            //watcher.Renamed += new RenamedEventHandler(OnRenamed);

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            timer_keepalive = new System.Timers.Timer();
            timer_keepalive.Interval = 5000;
            timer_keepalive.Elapsed += new ElapsedEventHandler(timer_keepaliveEvent);
            timer_keepalive.Enabled = true;
        }

        private void timer_keepaliveEvent(object source, ElapsedEventArgs e)
        {
            if (connectToolsnet)
            {
                string seqnum06 = ToolsNetUtil.makelenstr(ToolsNetUtil.make06str());
                byte[] MsgSend06 = System.Text.Encoding.ASCII.GetBytes(seqnum06);

                ClientSocketData.Send(MsgSend06);

                ClientSocketData.BeginReceive(MsgBufferData, 0, MsgBufferData.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBackData), null);

            }

        }


        // Define the event handlers.
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is changed, created, or deleted.
            nowchangepathfile = e.FullPath;

            nowchangefile = nowchangepathfile.Substring(nowchangepathfile.LastIndexOf("\\")+1, nowchangepathfile.Length - nowchangepathfile.LastIndexOf("\\")-1);

            while (!recordrunfile.Equals(nowchangepathfile))
            {
                csvStreamReader = new CsvStreamReader(recordrunfile);
                int i = csvStreamReader.ColCount;
                int ig = csvStreamReader.RowCount;

                ImportCsvToToolsnet();

                //DateTime dt = Convert.ToDateTime(ToolsNetUtil.getfiledate(recordrunfile));
                //dt.AddDays(1);


            }

        }

        private void ImportCsvToToolsnet()
        {
            //string seqnum04 = ToolsNetUtil.make04str(csvStreamReader[Int32.Parse(recordrunfilerow), 2]);
            //byte[] MsgSend04 = System.Text.Encoding.ASCII.GetBytes(seqnum04);
            //ClientSocketData.Send(MsgSend04);

            string seqnum06 = ToolsNetUtil.makelenstr(ToolsNetUtil.make06str());
            byte[] MsgSend06 = System.Text.Encoding.ASCII.GetBytes(seqnum06);
            ClientSocketData.Send(MsgSend06);

            ClientSocketData.BeginReceive(MsgBufferData, 0, MsgBufferData.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBackData), null);

        }

        private void timer_Main_Tick(object sender, EventArgs e)
        {
            nowdatefile = DateUtil.GetInstance().CurrentTime.ToString("d") + "_SG1.csv";
            txt_nowfile.Text = nowdatefile;
            txt_watchpath.Text = watchpath;
            txt_recordrunfilerow.Text = recordrunfilerow;
            txt_nowdatefile.Text = nowdatefile;
        }


    }
}
